package middleware

import (
	"admin-nexus-backend/pkg/logger"
	"admin-nexus-backend/pkg/response"
	"fmt"
	"runtime/debug"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

// Recovery 错误恢复中间件
func Recovery() gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				// 记录错误日志
				logger.Error("Panic recovered",
					zap.Any("error", err),
					zap.String("stack", string(debug.Stack())),
				)

				// 返回错误响应
				response.InternalServerError(c, fmt.Sprintf("服务器内部错误: %v", err))
				c.Abort()
			}
		}()

		c.Next()
	}
}
